import { Notify } from 'quasar'
// notification, Modal
import axios, { AxiosError } from "axios";

import { isEmpty } from "lodash-es";
import qs from "qs";
import pkg from "../../package.json";


declare module "axios" {
    export interface AxiosRequestConfig {
        useCommonErrorHandler?: boolean;
    }

    export interface AxiosInstance extends Axios {
        request<R, D = unknown>(config: AxiosRequestConfig<D>): Promise<R>;
        get<R, D = unknown>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
        delete<R, D = unknown>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
        head<R, D = unknown>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
        options<R, D = unknown>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
        post<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        put<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        patch<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        postForm<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        putForm<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        patchForm<R, D = unknown>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
    }
}

const http = axios.create({
    baseURL: import.meta.env.VITE_API_USE_PROXY === "true" ? "" : import.meta.env.VITE_API_HOST,
    headers: {
        "Content-Type": "application/json",
        "Client-Version": pkg.version,
    },
    useCommonErrorHandler: true,
});

const getToken = () => {
    return localStorage.getItem("autoLogin") === "true"
        ? localStorage.getItem("token")
        : sessionStorage.getItem("token");
};

http.interceptors.request.use(
    function (config) {
        const token = getToken();

        if (!isEmpty(token)) {
            config.headers.setAuthorization(`Bearer ${token}`);
        }

        if (config.params) {
            // GET请求不使用 axios 默认处理
            const url =
                config.url +
                "?" +
                qs.stringify(config.params, {
                    arrayFormat: "brackets",
                });
            console.debug(`请求地址：`, (config.baseURL || "") + url);
            console.debug(`请求头：`, config.headers);

            return {
                ...config,
                url,
                params: void 0,
            };
        }

        console.debug(`请求地址：`, (config.baseURL || "") + config.url);
        console.debug(`请求头：`, config.headers);
        console.debug(`请求参数：`, config.data);

        return config;
    },
    function (error) {
        return Promise.reject(error);
    },
);

// 添加响应拦截器
http.interceptors.response.use(
    function (response) {
        console.debug(`响应对象：`, response);
        if (response.status >= 200 && response.status < 300) {
            const data: ApiResponse = response.data;
            console.debug(`响应参数：`, data);

            if (data.code === "ERROR") {
                const { config } = response;

                if (config.useCommonErrorHandler) {
                    Notify.create(data.msg)
                }
                return Promise.reject(new AxiosError(data.msg, data.code, response.config, response.request, response));
            } else if (data.code === "UNAUTHORIZED") {
                const { config } = response;
                if (config.useCommonErrorHandler) {
                    Notify.create({
                        message: '认证信息已过期，请重新登录',
                        color: 'primary',
                        position:'bottom',
                        actions: [
                            { label: '登录', color: 'yellow', handler: () => {
                                    console.log('没执行')
                                    location.href = "/user/login?" +
                                                qs.stringify({
                                                    redirect: location.pathname + location.search,
                                                });
                                } },
                            { label: '取消', color: 'white', handler: () => { /* ... */ } }
                        ]
                    })
                }
                return Promise.reject(new AxiosError(data.msg, data.code, response.config, response.request, response));
            }
            return response.data;
        } else {
            return Promise.reject(
                new AxiosError(response.statusText, AxiosError.ERR_BAD_RESPONSE, response.config, void 0, response),
            );
        }
    },
    function (error) {
        if (error instanceof AxiosError) {
            const { config, message, response } = error;
            if (config?.useCommonErrorHandler) {
                // const { method, baseURL, url } = config;

                if (response) {
                    // notification.error({
                    //     message: `${response.status} - ${response.statusText}`,
                    //     description: `[${method?.toUpperCase()}] ${baseURL}${url}`,
                    // });
                    Notify.create(message)

                } else {
                    Notify.create(message)
                    // notification.error({
                    //     message: `${message}`,
                    //     description: `[${method?.toUpperCase()}] ${baseURL}${url}`,
                    // });
                }
            }
        }
        return Promise.reject(error);
    },
);

export default http;
